/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jhu.profiteer;

import jhu.profiteer.data.Character;
import jhu.profiteer.data.CharacterJpaController;
import jhu.profiteer.data.Account;
import jhu.profiteer.data.AccountJpaController;
import jhu.profiteer.data.Airplane;
import jhu.profiteer.data.AirplaneJpaController;
import jhu.profiteer.data.Commodity;
import jhu.profiteer.data.CommodityJpaController;
import jhu.profiteer.data.CurrentCommodityValue;
import jhu.profiteer.data.CurrentCommodityValueJpaController;
import jhu.profiteer.data.AirplaneCargo;
import jhu.profiteer.data.AirplaneCargoJpaController;
import jhu.profiteer.data.exceptions.NonexistentEntityException;

import java.util.ArrayList;
import java.util.Vector;
import java.util.Iterator;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;

import javax.persistence.NoResultException;

/**
 *
 * @author sclee
 */
public class MarketServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

System.out.println("Market Servlet");
        HttpSession session = request.getSession();
        Vector<String> notices = (Vector<String>)session.getAttribute("notices");
        if (notices == null) notices = new Vector<String>();

        Account account = null;
        Character character = null;
        Airplane airplane = null;
        String url = null;
        boolean accountDamaged = false;
        ArrayList<CurrentCommodityValue> cvlist = new ArrayList<CurrentCommodityValue>();
        ArrayList<Commodity> clist = new ArrayList<Commodity>();
        ArrayList<AirplaneCargo> aclist = new ArrayList<AirplaneCargo>();

        // Search for a session attribute "character"
        character = (Character)session.getAttribute("character");
        account = (Account)session.getAttribute("account");

        // CREATE TEMPORARY CHARACTER
        //Character c = new Character();
        /*
        character = new Character();
        character.setAccountId(Long.valueOf(1));
        character.setCurrentLocationId(Long.valueOf(1));
        character.setId(Long.valueOf(1));
        character.setMoney(Long.valueOf(1000));
        character.setName("PLAYER1");
        character.setDescription("TRAVELLER");
*/
        // Search for a character from the database if no character in session
        if (character == null) {
System.out.println("character is null");
            // Redirect to Index page if no account is found
            if (account == null) {
                System.out.println("account is null");
                url = "/index.jsp";
            }
            else {
                // Check if a character exists for this account
                CharacterJpaController cjc = new CharacterJpaController();
                character = cjc.findCharacter(account.getId());

                // Redirect to CharacterInformation page if no character is found
                if (character == null) {
                    url = "/characterInformation";
                }
            }
        }

        // Character is found
        if (character != null) {
            System.out.println("character is found");
            // find airplane from session
           
            airplane = (Airplane) session.getAttribute("airplane");

            if (airplane == null) {

                // find airplane from database
                AirplaneJpaController ajc = new AirplaneJpaController();
                try {
                    if (ajc.testForAirplaneWithCharacterId(character.getId())) {
                    airplane = ajc.findAirplaneByCharacterId(character.getId());
                    }
                    else {
                        System.out.println("ACCOUNT DAMAGED 1");
                        accountDamaged = true;
                    }
                } catch (NoResultException ne) {
                    ne.printStackTrace();
                   
                }
            }

            // Search for all currentCommodityValue objects
            CurrentCommodityValueJpaController cvjc = new CurrentCommodityValueJpaController();

            cvlist = (ArrayList<CurrentCommodityValue>)cvjc.findCurrentCommodityValuesByCharacterId(character.getId());

            if (cvlist.isEmpty()) {
                System.out.println("ACCOUNT DAMAGED 2");
                accountDamaged = true;
            }
        }



        if (url == null) {
            if (accountDamaged) {
                url = "/logout";
                if (account != null) {
                    account.setDamaged(true);
                    AccountJpaController acjc = new AccountJpaController();
                    try {
                        acjc.edit(account);
                    } catch (NonexistentEntityException nee) {
                        nee.printStackTrace();
                        notices.add("No account with that ID exists.");
                    } catch (Exception e) {
                        e.printStackTrace();
                        notices.add("Error editing account.");
                    }
                    notices.add("This account has been damaged and needs to be " + "reviewed by a game administrator.  An administrator " + "will contac you once the account has been examined " + "and a solution has been implemented.");
                }
            } else {
                Iterator it = cvlist.iterator();
                while (it.hasNext()) {
                    ///CurrentCommodityValue temp = (CurrentCommodityValue)cvlist.get(0);
                    //System.out.println("comId:"+temp.getId().getCommodityId());
                     //System.out.println("charId:"+temp.getId().getCharacterId());
                      //System.out.println("price:"+temp.getPrice());
                    CurrentCommodityValue ccv = (CurrentCommodityValue)it.next();
                    CommodityJpaController cjc = new CommodityJpaController();
                    //System.out.println("ccv.getComId"+ccv.getId().getCommodityId());
                    Commodity commodity = cjc.findCommodity(ccv.getId().getCommodityId());
                    if (commodity == null) {
                        CurrentCommodityValueJpaController cvjc = new CurrentCommodityValueJpaController();

                        try {
                            cvjc.destroy(ccv.getId().getCommodityId(), ccv.getId().getCharacterId());
                            cvlist.remove(ccv);
                        } catch (NonexistentEntityException nee) {
                            nee.printStackTrace();
                            notices.add("No CurrentCommodityValue with that ID exists.");
                        } catch (Exception e) {
                            e.printStackTrace();
                            notices.add("Error deleting CurrentCommodityValue.");
                        }
                    } else {
                        clist.add(commodity);
                        if (airplane != null) {
                            AirplaneCargoJpaController acjc = new AirplaneCargoJpaController();

                            if (acjc.testForAirplaneCargo(airplane.getId(), ccv.getId().getCommodityId())) {
                            AirplaneCargo ac = acjc.findAirplaneCargo(airplane.getId(), ccv.getId().getCommodityId());                         
                                aclist.add(ac);
                            }
                            else {
                                aclist.add(null);
                            }
                            
                        }
                    }
                }
                url = "/market.jsp";
            }
        }

        // START TEST DATA
        /*
        CurrentCommodityValue ccv1 = new CurrentCommodityValue();
        ccv1.setCharacterId(Long.valueOf(1));
        ccv1.setCommodityId(Long.valueOf(1));
        ccv1.setPrice(Long.valueOf(24));
        CurrentCommodityValue ccv2 = new CurrentCommodityValue();
        ccv2.setCharacterId(Long.valueOf(1));
        ccv2.setCommodityId(Long.valueOf(2));
        ccv2.setPrice(Long.valueOf(12));
        CurrentCommodityValue ccv3 = new CurrentCommodityValue();
        ccv3.setCharacterId(Long.valueOf(1));
        ccv3.setCommodityId(Long.valueOf(3));
        ccv3.setPrice(Long.valueOf(100));

        Commodity c1 = new Commodity();
        c1.setId(Long.valueOf(1));
        c1.setDescription("Green Apple");
        c1.setName("Apple");
        Commodity c2 = new Commodity();
        c2.setId(Long.valueOf(2));
        c2.setDescription("California Orange");
        c2.setName("Orange");
        Commodity c3 = new Commodity();
        c3.setId(Long.valueOf(3));
        c3.setDescription("Yellow Banana");
        c3.setName("Banana");

        AirplaneCargo ac1 = new AirplaneCargo();
        ac1.setAirplaneId(Long.valueOf(1));
        ac1.setCommodityId(Long.valueOf(1));
        ac1.setQuantity(Long.valueOf(30));
        AirplaneCargo ac2 = new AirplaneCargo();
        ac2.setAirplaneId(Long.valueOf(1));
        ac2.setCommodityId(Long.valueOf(2));
        ac2.setQuantity(Long.valueOf(10));
        AirplaneCargo ac3 = null;



        clist.add(c1);
        clist.add(c2);
        clist.add(c3);

        cvlist.add(ccv1);
        cvlist.add(ccv2);
        cvlist.add(ccv3);

        aclist.add(ac1);
        aclist.add(ac2);
        aclist.add(ac3);

        url = "/market.jsp";
        // END TEST DATA
*/

        // Set session variables
        session.setAttribute("clist", clist);
        session.setAttribute("cvlist", cvlist);
        session.setAttribute("aclist", aclist);
        session.setAttribute("character",character);
        session.setAttribute("account",account);
        session.setAttribute("notices",notices);

System.out.println("url: "+url);

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
        System.out.println("dispatcher: "+dispatcher);
        dispatcher.forward(request, response);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
